/**
 * author:wos
 * time:2024-1-4
 * title:新增，修改目录权限
 */
const {makeSqlUpdate, makeSqlInsert, makeSqlSelect} = require('../../../utils/makeSql'),
    {formatTime} = require("../../../utils/timestamp"),
    parseQueryParams = require("../../../utils/parseQueryParams"),
    md5 = require("md5");

async function edit(ctx, next) {
    let sql = ''
    const body = Object.assign({}, ctx.request.body)
    let data = Object.assign({}, body)
    const postIds = data.postIds
    const roleIds = data.roleIds
    delete data.dept
    delete data.postIds
    delete data.roleIds

    //更新数据
    if (ctx.request.method === 'PUT') {
        //判断dict_type是否重复
        const rsLen = await global.query(`SELECT userId FROM sys_user WHERE userId <> ${body.userId} AND username = '${body.username}'`)
        if (rsLen.length > 0){
            global.response(ctx, {
                "status": 200,
                "code": 500,
                "data": '',
                "msg": '用户名已经被使用'
            })
            return
        }

        const updateSqlConfig = {
            tableName: "sys_user",
            noUpdateKey: ['userId', 'createBy', 'createTime', 'version',"password", "type","delFlag","lastLoginTime","lastLoginIp","permissions","roles"],
            autoUpdate: {"updateBy": ctx.username, "updateTime": formatTime()},
            where: ['userId']
        }
        sql = makeSqlUpdate(data, updateSqlConfig)

        try {
            if (!sql) {
                global.response(ctx, {
                    "status": 200,
                    "code": 500,
                    "data": rs,
                    "msg": '参数错误'
                })
                return
            }
            let rs = await global.query(sql)
            await doit(data.userId, postIds, roleIds)
            global.response(ctx, {
                "status": 200,
                "code": 200,
                "data": rs,
                "msg": 'success'
            })
        } catch (err) {
            global.serverError(ctx)
        }




    //新建数据
    } else if (ctx.request.method === 'POST') {
        const rsLen = await global.query(`SELECT userId FROM sys_user WHERE username = '${body.username}'`)
        if (rsLen.length > 0){
            global.response(ctx, {
                "status": 200,
                "code": 500,
                "data": '',
                "msg": '用户名已经被使用'
            })
            return
        }

        const insertSqlConfig = {
            tableName: "sys_user",
            noUpdateKey: ["password"],
            autoUpdate: {"createBy": ctx.username, "createTime": formatTime(), password:md5(data.password)},
        }
        sql = makeSqlInsert(data, insertSqlConfig)

        try {
            if (!sql) {
                global.response(ctx, {
                    "status": 200,
                    "code": 500,
                    "data": rs,
                    "msg": '参数错误'
                })
                return
            }
            let rs = await global.query(sql)
            await doit(rs.insertId, postIds, roleIds)
            global.response(ctx, {
                "status": 200,
                "code": 200,
                "data": rs,
                "msg": 'success'
            })
        } catch (err) {
            global.serverError(ctx)
        }
    } else {
        global.serverError(ctx)
    }


}


//新增岗位，角色
async function doit(userId,postIds,roleIds){
    let sql = `DELETE FROM sys_user_role WHERE userId = ${userId}; DELETE FROM sys_user_post WHERE userId = ${userId};`
    for (let i in postIds){
        sql += `INSERT INTO sys_user_post (userId,postId) VALUES (${userId},${postIds[i]});`
    }
    for(let i in roleIds){
        sql += `INSERT INTO sys_user_role (userId,roleId) VALUES (${userId},${roleIds[i]});`
    }
    console.log(sql)
    await global.query(sql)
}


module.exports = edit